# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from vmwarelib import inventory
from vmwarelib.serialize import MyJSONEncoder
from vmwarelib.actions import BaseAction
import json
from pyVmomi import vim


class GetVMGuestInfo(BaseAction):
    def run(self, template_vm_name, new_vm_name, datacenter_name='SmarchitDC', vsphere=None):
        """
        Retrieve Guest Info for given Virtual Machines

        Args:
        - template_vm_name: vm name as template
        - new_vm_name: vm name will be cloned
        - vsphere: Pre-configured vsphere connection details (config.yaml)


        Returns:
        - dict: Virtual machine details.
        """

        results = {}
        if not template_vm_name or not new_vm_name:
            raise ValueError("No template_vm_name nor new_vm_name provided.")

        is_success = True
        self.establish_connection(vsphere)

        vm = inventory.get_virtualmachine(self.si_content, name=template_vm_name)
        if vm:
            datacenter = inventory.get_datacenter(self.si_content, name=datacenter_name)

            datastore = inventory.get_datastore(self.si_content, name=vm.datastore[0].info.name)
            relospec = vim.vm.RelocateSpec()
            relospec.datastore = datastore
            # relospec.pool = resource_pool

            clonespec = vim.vm.CloneSpec()
            clonespec.location = relospec
            # clonespec.powerOn = power_on

            task = vm.Clone(name=new_vm_name, folder=datacenter.vmFolder, spec=clonespec)

            self._wait_for_task(task)
            if task.info.state != vim.TaskInfo.State.success:
                is_success = False
                self.logger.warning(task.info.error.msg)

            return (is_success, {'task_id': task._moId, 'vm_id': task.info.result._moId})

        else:
            return (False, {'err_msg': 'template is not existed.'})

